package com.apestech.framework.sql.table;

import com.apestech.framework.cache.Cache;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.MultiDataBase;
import com.apestech.framework.sql.SqlUtil;
import com.apestech.framework.sql.condition.ConditionMap;
import com.apestech.framework.sql.modul.SqlList;
import com.apestech.framework.util.ExceptionUtil;
import com.apestech.framework.xml.sql.modul.SqlRule;

import java.util.ArrayList;

/**
 * @author hup
 * @create 2018-08-30-11:55
 */
public class TableUpdate extends SqlUtil {

    private String sql;
    private String schema;
    private ConditionMap param;
    private SqlList sqlparam=new SqlList();

    public TableUpdate(ConditionMap param) throws Exception {
        this.param=param;
    }

    public void setSchema(String schema) {
        this.schema = schema;
    }

    public void getTableSql() throws Exception {
        sqlparam=new SqlList();
        sql= (String) Cache.getKey(param.getCacheKey());
        if(sql==null || param.isParamField()){
            sql=getUpdateCol();
            if(!param.isParamField()) Cache.setKey(param.getCacheKey(), sql);
        }
        sql=addSql(param.getFromtab(), sql, param, sqlparam, "");
    }

    private String getUpdateCol() throws Exception {
        String tabName="";
        try {
            tabName=param.getFromtab().getTabName();
            if(schema!=null) tabName=schema+"."+tabName;
            String fields=param.getSqlruleFields(tabName);
            boolean in=!param.getSqlruleNotIn(tabName);
            Table table=param.getFromtab().getDictTable(tabName);
            SqlRule.Table sqltab=param.getSqlruleTable(tabName);
            String key="";
             if(table.getPkKey()!=null) {
                 key = table.getPkKey().getPkColumn();
            }
            if(sqltab!=null){
                 if(sqltab.getWherefield()!=null) key=sqltab.getWherefield();
            }
            String col=getCol(table.getColumn(), fields, in);
            if(param.isParamField()){
                ArrayList<String> klist=param.getSingle().getKeylist();
                int klen=klist.size();
                String ncol="";
                for(int k=0; k<klen; k++){
                    String field=klist.get(k);
                    if((","+col+",").indexOf(","+field+",")>=0){
                        if(!ncol.equals("")) ncol=ncol+",";
                        ncol=ncol+field;
                    }
                }
                col=ncol;
            }
            col=col+",";
            String updateCol="";
            String[] list=col.split(",");
            int len=list.length;
            int klen=0;
            if(key==null || "".equals(key)) key=fields.replace(",",";");
            if(key!=null && !"".equals(key)) klen=key.split(";").length;
            for(int i=0; i<len; i++){
                String s=list[i];
                if(s!=null && key.length()>0){
                    if((";"+key+";").indexOf(";"+s+";")<0 || len==klen){
                        if(!"".equals(updateCol)){
                            updateCol=updateCol+",";
                        }
                        if(len==klen) updateCol=updateCol+s+"=#{"+s+"_OLD"+"}";
                        else{
                            if(param.isTimeControl() && param.getTimeField().equals(s)){
                                if(!"".equals(key)) key=key+";";
                                key=key+s;
                                updateCol=updateCol+s+"=#{"+s+"_NEW"+"}";
                                //MultiDataBase db=new MultiDataBase(param.getFromtab().getDbType());
                                //updateCol=updateCol+s+"="+db.getTimeStamp();
                            } else updateCol=updateCol+s+"=#{"+s+"}";
                        }
                    }
                }
            }
            if("".equals(updateCol)){
                return null;
            }
            if(sqltab!=null && sqltab.getField()!=null){
                len=sqltab.getField().size();
                ArrayList<String> klist=sqltab.getField().getKeylist();
                for(int i=0; i<len; i++){
                    String k=klist.get(i);
                    JSONObject m= (JSONObject) sqltab.getField().get(k);
                    String nbsql=getSelectSql(m);
                    if(nbsql!=null){
                        nbsql=nbsql.replace("#{KEY}", param.getFromtab().getTabName()+"."+k);
                        updateCol=updateCol+","+k+"=("+nbsql+")";
                    }
                }
            }
            String rsql=" UPDATE "+tabName+" SET "+updateCol+getKeyWhere(key, true, table.getColumn(), param.getTimeField(), param.isTimeControl());  //col
            if(param.getSql()!=null) rsql=rsql+" "+param.getSql();
            sql=rsql;
            return rsql;
        } catch (Exception e) {
            ExceptionUtil.exception(this, "getUpdate", e.getMessage());
        }
        return null;
    }

    public SqlList getSqlparam() {
        return sqlparam;
    }

    public String getSql() {
        return sql;
    }
}
